import React, {Component, Fragment} from 'react'

import Lightbox from 'react-image-lightbox'
import 'react-image-lightbox/style.css' // This only needs to be imported once in your app

import {
  Empty,
  Affix,
} from 'antd'
import {connect} from 'dva'

@connect(({lightbox}) => ({lightbox}))
export default class Article extends Component {
  componentDidUpdate(prevProps) {
    if (!window.location.hash && this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
    const {hash} = this.props.location
    this.scrollToAnchor(hash)
    if (document.querySelectorAll('.toc-affix').length) {
      this.bindScroller()
    }
  }

  bindScroller() {
    const self = this
    if (this.scroller) {
      this.scroller.disable()
    }
    require('intersection-observer') // eslint-disable-line
    const scrollama = require('scrollama') // eslint-disable-line
    this.scroller = scrollama()
    this.scroller.setup({
      step: '.markdown-body h2,.markdown-body h3', // required
      offset: 0,
    }).onStepEnter(({element}) => {
      document.querySelectorAll('.toc-affix li a').forEach(v => v.className = '')
      const currentNode = document.querySelectorAll(`.toc-affix li a[href="#${element.id}"]`)[0]
      if (currentNode) {
        let node = currentNode.parentElement
        if (node && node.nextSibling) {
          node = node.nextSibling
          while (node.nodeType === 3) {
            node = node.nextSibling
          }

          node = node.firstElementChild
          while (node.nodeType === 3) {
            node = node.nextSibling
          }

          node.className = 'current'
        } else {
          currentNode.className = 'current'
        }
      }
    })
  }

  scrollToAnchor = (anchorName) => {
    if (anchorName && anchorName.length > 1) {
      anchorName = decodeURIComponent(anchorName.substr(1))
      let anchorElement = document.getElementById(anchorName)
      if (anchorElement) {
        anchorElement.scrollIntoView()
      }
    }
  }

  handleCloseRequest = () => {
    const {dispatch} = this.props
    dispatch({
      type: 'lightbox/close',
      payload: {
        isOpen: false,
      },
    })
  }

  render() {
    const {currentArticle, loading, lightbox, renderMarkdown} = this.props
    const content = currentArticle.content || ''
    const markContent = renderMarkdown(content)
    return (
      <Fragment>
        {content ? (
            <article className="markdown-body">
              <div dangerouslySetInnerHTML={{__html: markContent.html}}/>
              {lightbox.isOpen && (
                <Lightbox mainSrc={lightbox.src} onCloseRequest={this.handleCloseRequest}/>)}
            </article>) :
          (!loading && <Empty description={<span>暂无内容！</span>} style={{padding: 150}}/>)
        }
        {!markContent.toc || markContent.toc.length <= 1 ? null : (
          <Affix className="toc-affix" offsetTop={16}>
            <div dangerouslySetInnerHTML={{__html: markContent.toc}}/>
          </Affix>
        )}
      </Fragment>
    )
  }
}
